package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.ICommentHotService;
import com.heima.comment.service.ICommentService;
import com.heima.feign.clients.UserClient;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentQueryDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentService implements ICommentService {

    @Autowired  //阿里云内容安全检查
    private GreenTextScan greenTextScan;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ICommentHotService commentHotService;

    /**
     * APP 端-文章详情页-发表文章评论
     * @param commentSaveDTO
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO commentSaveDTO) {
        //1.校验参数
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.保存文章评论数据
            //2.1对评论内容进行安全检查
        commentContentScan(commentSaveDTO);
            //2.2查询发表评论的用户信息
        ResponseResult<ApUser> userResult = userClient.findUserById(loginId);
        if(userResult.getCode().intValue() != 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR, userResult.getErrorMessage());
        }
        ApUser apUser = userResult.getData();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前发表评论用户的信息不存在,请联系管理员");
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(commentSaveDTO.getArticleId());
        apComment.setType((short) 0);   //【0 - 文章】
        //apComment.setChannelId();
        apComment.setContent(commentSaveDTO.getContent());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);   //【0 - 普通评论】
        //apComment.setLongitude();
        //apComment.setLatitude();
        //apComment.setAddress();
        //apComment.setOrd();
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.save(apComment);
        //3.返回响应
        return ResponseResult.okResult();
    }

    /**
     * APP 端-文章详情页-对文章评论点赞/取消点赞
     * @param commentLikeDTO
     * @return
     */
    @Override
    public ResponseResult handleLike(CommentLikeDTO commentLikeDTO) {
        //1.校验参数
            //1.1校验登陆状态
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
            //1.2检查点赞的评论是否存在
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentLikeDTO.getCommentId())), ApComment.class);
        if(apComment == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "点赞的评论不存在");
        }
            //1.3检查是否重复点赞
        ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("author_id").is(loginId).and("comment_id").is(commentLikeDTO.getCommentId())), ApCommentLike.class);
        if(apCommentLike != null && commentLikeDTO.getOperation().intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "已经点过赞，请勿重复点赞");
        }
        //2.处理文章评论点赞或取消点赞
        if(commentLikeDTO.getOperation().intValue() == 0){
            //点赞
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            /*0 普通评论 1 热点评论* 2 推荐评论* 3 置顶评论* 4 精品评论* 5 大V 评论*/
            //判断当前点赞的评论是否有资格称为热点评论
            if(apComment.getLikes().intValue() >= 10 && apComment.getFlag().shortValue() == 0){
                commentHotService.hotCommentExecutor(apComment);
            }

            apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(loginId);
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(commentLikeDTO.getOperation());
            mongoTemplate.save(apCommentLike);
        }else {
            //取消点赞
            apComment.setLikes(apComment.getLikes() - 1 < 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);

            mongoTemplate.remove(Query.query(Criteria.where("author_id").is(loginId).and("comment_id").is(commentLikeDTO.getCommentId())), ApCommentLike.class);
        }
        //3.响应结果
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * APP 端-文章详情页-查询文章评论列表
     * @param commentQueryDTO
     * @return
     */
    @Override
    public ResponseResult listComment(CommentQueryDTO commentQueryDTO) {
        //1.校验参数
            //1.1校验分页参数
        if(commentQueryDTO.getSize() == null || commentQueryDTO.getSize().intValue() <= 0){
            commentQueryDTO.setSize(10);    //默认每页展示 10 条评论
        }

        //2.分页查询文章列表
        List<ApComment> apCommentList = null;
            //2.1判断当前页面是否是评论首页
        if(commentQueryDTO.getIndex() != 1){
            //2.1.1否，直接查询最近发布的 10 条评论
            Query query = Query.query(Criteria.where("article_id").is(commentQueryDTO.getArticleId()).and("created_time").lt(commentQueryDTO.getMinDate())).limit(commentQueryDTO.getSize()).with(Sort.by(Sort.Direction.DESC, "created_time"));
            apCommentList = mongoTemplate.find(query, ApComment.class);
        }else {
            //2.2是，查询由热门评论组成的集合
            apCommentList = mongoTemplate.find(Query.query(Criteria.where("article_id").is(commentQueryDTO.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
            //2.3判断热门评论集合是否为空
            if (CollectionUtils.isEmpty(apCommentList)) {
                //2.3.1是，直接查询最近发布的 10 条普通评论
                Query query = Query.query(Criteria.where("article_id").is(commentQueryDTO.getArticleId()).and("created_time").lt(commentQueryDTO.getMinDate())).limit(commentQueryDTO.getSize()).with(Sort.by(Sort.Direction.DESC, "created_time"));
                apCommentList = mongoTemplate.find(query, ApComment.class);
            }else {
                //2.4否，查询最近发布的 (10 - 热门评论数) 条普通评论
                Query query = Query.query(Criteria.where("article_id").is(commentQueryDTO.getArticleId()).and("created_time").lt(commentQueryDTO.getMinDate()).and("flag").is(0)).limit(commentQueryDTO.getSize() - apCommentList.size()).with(Sort.by(Sort.Direction.DESC, "created_time"));
                List<ApComment> normalCommentList = mongoTemplate.find(query, ApComment.class);
                apCommentList.addAll(normalCommentList);
            }
        }
        //3.返回响应
            //3.1用户未登录，直接返回评论列表
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.okResult(apCommentList);
        }
            //3.2用户已登录,对当前用户点赞过的评论进行特殊处理
        ArrayList<ApCommentVO> apCommentVOList = new ArrayList<>();
                //3.2.1获取待展示评论列表的所有评论的 id 集合
        List<String> apCommentIdList = apCommentList.stream().map(apComment -> apComment.getId()).collect(Collectors.toList());
                //3.2.2获取当前用户点赞过的评论列表
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("author_id").is(loginId).and("comment_id").in(apCommentIdList)), ApCommentLike.class);
                //3.2.3封装 ApComment 为 ApCommentVO
        if(!CollectionUtils.isEmpty(apCommentList) && !CollectionUtils.isEmpty(apCommentLikes)){
            apCommentList.stream().forEach(apComment -> {
                ApCommentVO apCommentVO = new ApCommentVO();
                BeanUtils.copyProperties(apComment,apCommentVO);
                apCommentLikes.stream().forEach(apCommentLike -> {
                    if(apCommentLike.getCommentId().equals(apComment.getId())){
                        apCommentVO.setOperation((short) 0);
                    }
                });
                apCommentVOList.add(apCommentVO);
            });
            return ResponseResult.okResult(apCommentVOList);
        }
        return ResponseResult.okResult(apCommentList);
    }

    /**
     * 接入阿里云内容安全检测
     * @param commentSaveDTO
     */
    private void commentContentScan(CommentSaveDTO commentSaveDTO) {
        try {
            Map resultMap = greenTextScan.greenTextScan(commentSaveDTO.getContent());
            if("block".equalsIgnoreCase((String) resultMap.get("suggestion")) || "review".equalsIgnoreCase((String) resultMap.get("suggestion"))){
                String filteredContent = (String) resultMap.get("filteredContent");
                //将原始敏感评论替换为敏感词被屏蔽后的内容
                commentSaveDTO.setContent(filteredContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接入阿里云文本内容审核失败，失败原因: {}", e.getMessage());
        }
    }
}
